package com.runa.persistence.sort;

import com.runa.persistence.StringUtil;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 2024/2/20 16:37
 * zhangYB
 */
@Slf4j
public class SortComparator<T> implements Comparator<T> {

    private Class<?> clazz = null;
    private Field sortField = null;
    private String sort;
    private String order;

    public SortComparator(String sort, String order) {
        this.sort = sort;
        this.order = order;
    }

    @Override
    public int compare(T t1, T t2) {
        if (sortField == null) {
            clazz = t1.getClass();
            Field[] declaredFields = clazz.getDeclaredFields();
            for (Field declaredField : declaredFields) {
                if (declaredField.getName().equals(sort)) {
                    sortField = declaredField;
                    sortField.setAccessible(true);
                }
            }
        }


        if (sortField != null) {
            try {
                String typeName = sortField.getType().getName();
                switch (typeName) {
                    case "java.lang.String":
                        String v1 = (String) sortField.get(t1);
                        String v2 = (String) sortField.get(t2);
                        if ("ASC".equalsIgnoreCase(order)) {
                            return v1.compareTo(v2);
                        } else if ("DESC".equalsIgnoreCase(order)) {
                            return v2.compareTo(v1);
                        }
                        break;
                    case "java.lang.Boolean":
                        Boolean b1 = (Boolean) sortField.get(t1);
                        Boolean b2 = (Boolean) sortField.get(t2);
                        if ("ASC".equalsIgnoreCase(order)) {
                            return b1.compareTo(b2);
                        } else if ("DESC".equalsIgnoreCase(order)) {
                            return b2.compareTo(b1);
                        }
                        break;
                }






            } catch (IllegalAccessException e) {
                log.error("get field value: ", e);
            }
        }



        return 0;
    }

    public void finish() {
        if (sortField != null) {
            sortField.setAccessible(false);
        }
    }

    public void sorted(List<T> list) {
        if (StringUtil.isBlank(sort) || StringUtil.isBlank(order)) {
            return;
        }
        Collections.sort(list, this);
    }

}
